package com.wxg.demo.ch01.day02;

import java.lang.reflect.Constructor;
import java.lang.reflect.Parameter;
import java.util.Arrays;
import java.util.List;

public class Args02 {
    public static <T> T parse(Class<T> optionClass, String... args) {
        try {
            List<String> argsList = Arrays.asList(args);
            Constructor<?> constructor = optionClass.getDeclaredConstructors()[0];//反射API
            Parameter[] parameters = constructor.getParameters();//反射API: 构造函数的参数
            Object[] values = Arrays.stream(parameters).map(it -> getParameterValue(argsList, it)).toArray();

            return (T) constructor.newInstance(values);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static Object getParameterValue(List<String> argsList, Parameter parameter) {
        Option02 option = parameter.getAnnotation(Option02.class);//反射API: 构造函数参数上的注解

        Object value = null;
        if (parameter.getType() == boolean.class) {
            value = argsList.contains("-" + option.value());
        }
        if (parameter.getType() == int.class) {
            int index = argsList.indexOf("-" + option.value());
            value = Integer.parseInt(argsList.get(index + 1)); // 这里必须转换成正确的类型, 测试中写的是 8080 而不是 "8080"
        }
        if (parameter.getType() == String.class) {
            int index = argsList.indexOf("-" + option.value());
            value = argsList.get(index + 1);
        }
        return value;
    }
}
